<?php
namespace app\api\controller\wanlshop;

use addons\wanlshop\library\WanlPay\WanlPay;
use addons\wanlshop\library\WanlSdk\Common;
use app\common\controller\Api;
use think\Cache;
use think\Db;
use think\Exception;


/**
 * 团队 和 金额
 */
class Team extends Api
{
    protected $noNeedLogin = [/*'*'*/];
	protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();error_reporting(0);
    }

    /**
     *share to prel
     */
    public function getshare()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost())
        {
            $shareid = $this->request->post('shareid');
            if($shareid == $this->auth->id) $this->error('不可以推荐自己');
            if(!\app\common\model\Team::where('get_user_id',$this->auth->id)->find()){
                model('\app\common\model\Team')->save([
                    'user_id' => $shareid,
                    'get_user_id' => $this->auth->id
                ]);
            }
            $this->success('返回成功');
        }
        $this->error(__('非法请求'));
    }

    /**
     *team on
     */
    public function teamindex()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()){
            $tyid = $this->request->post('typeid');
            $word = $this->request->post('keyword');
            $teamres = model('\app\common\model\Team')->where('user_id',$this->auth->id)->select();
            $indexmen = \app\common\model\User::where('id',$this->auth->id)->find();
            $mobile = $indexmen['mobile'];
            $url = 'https://admin.yuanzai1999.com/api/userinfo';
            $data ['mobile'] = $mobile;
            $param = [
                'nonce_str'=>'test234',
                'platform' =>1,
                'data'=>json_encode($data)
            ];
            //生成签名
            $param['sign'] = $this->createSign($param);
            $yuanzai_res = curl_request($url,true,$param);
            $tem['user_id'] = $yuanzai_res['data']['data']['id'];
            $url = 'https://admin.yuanzai1999.com/api/team';
            unset($param['sign']);$param['data'] = json_encode($tem);$param['sign'] = $this->createSign($param);
            if($yuanzai_res['data']['data']['id']) $yuanzaitem_res = curl_request($url,true,$param);
            if(count($yuanzaitem_res['data']['data']['group_data'][1]['list'])>10) $yuanzaitem_res['data']['data']['group_data'][1]['list']=array_slice($yuanzaitem_res['data']['data']['group_data'][1]['list'],-3,2);
            if(count($yuanzaitem_res['data']['data']['group_data'][2]['list'])>10) $yuanzaitem_res['data']['data']['group_data'][2]['list']=array_slice($yuanzaitem_res['data']['data']['group_data'][2]['list'],-3,2);
            if(count($yuanzaitem_res['data']['data']['group_data'][3]['list'])>10) $yuanzaitem_res['data']['data']['group_data'][3]['list']=array_slice($yuanzaitem_res['data']['data']['group_data'][3]['list'],-3,2);
            if(count($yuanzaitem_res['data']['data']['group_data'][4]['list'])>10) $yuanzaitem_res['data']['data']['group_data'][4]['list']=array_slice($yuanzaitem_res['data']['data']['group_data'][4]['list'],-3,2);
            $indexnick = $indexmen['nickname'];
            if($indexmen['level'] == 4) $commures = \app\common\model\AddressLocation::where('uid',$this->auth->id)->select();
            foreach($commures as $vale){
                $subdsres[] = \app\common\model\AddressLocation::where('town_id',$vale['town_id'])->where('subdstrict_id','NEQ',0)->select();
            }
            $subdsresto = array_unique($subdsres, SORT_REGULAR);
            foreach($subdsresto as $vals){
                foreach($vals as $valch){
                    $subdsarr = \app\common\model\User::where('id',$valch['uid'])->find();
                    $souceres[] = [
                        'avatar' => $subdsarr['avatar'],
                        'nickname' => $subdsarr['nickname'],
                        'time' => date('Y-m-d',$subdsarr['createtime']),
                        'indexnickname' => $indexnick,
                        'totalaccount' => ""
                    ];
                    $seaharr = \app\common\model\User::where('id',$valch['uid'])->where('mobile','LIKE',"%{$word}%")->find() ?: \app\common\model\User::where('id',$valch['uid'])->where('nickname','LIKE',"%{$word}%")->find();
                    if($word && $seaharr){
                        $seahres[] = [
                            'avatar' => $seaharr['avatar'],
                            'nickname' => $seaharr['nickname'],
                            'time' => date('Y-m-d',$seaharr['createtime']),
                            'indexnickname' => $indexnick,
                            'totalaccount' => ""
                        ];
                    }
                }
            }
            if($tyid == 3 && $indexmen['level'] == 4){
                foreach($souceres as $valso){
                    foreach($yuanzaitem_res['data']['data']['group_data'][3]['list'] as $k=>$valx){
                        if($valso['nickname'] == $valx['username']){
                            unset($yuanzaitem_res['data']['data']['group_data'][3]['list'][$k]);
                        }
                    }
                }
                foreach($yuanzaitem_res['data']['data']['group_data'][3]['list'] as $vali){
                    $souceres[] = $seahres[] = [
                        'avatar' => $vali['avatar'],
                        'nickname' => $vali['username'],
                        'time' => substr($vali['create_time'],0,10),
                        'indexnickname' => $indexnick,
                        'totalaccount' => ""
                    ];
                }
                $listres = $word ? $seahres : $souceres;
            }else{
                foreach($teamres as $val){
                    $useres = \app\common\model\User::where('id',$val['get_user_id'])->find();
                    $seahuseres = \app\common\model\User::where('id',$val['get_user_id'])->where('mobile','LIKE',"%{$word}%")->find() ?: \app\common\model\User::where('id',$val['get_user_id'])->where('nickname','LIKE',"%{$word}%")->find();
                    if($useres['level'] == $tyid){
                        if($word && $seahuseres){
                            $listres[] = [
                                'avatar' => $seahuseres['avatar'],
                                'nickname' => $seahuseres['nickname'],
                                'time' => date('Y-m-d',$seahuseres['createtime']),
                                'indexnickname' => $indexnick,
                                'totalaccount' => ""
                            ];
                        }
                        if(!$word){
                            $listres[] = [
                                'avatar' => $useres['avatar'],
                                'nickname' => $useres['nickname'],
                                'time' => date('Y-m-d',$useres['createtime']),
                                'indexnickname' => $indexnick,
                                'totalaccount' => ""
                            ];
                        }
                    }
                }
                $xinmemarr = array_values(array_column($yuanzaitem_res['data']['data']['group_data'][$tyid]['list'], NULL, 'username'));
                foreach($listres as $valis){
                    foreach($xinmemarr as $m=>$valu){
                        if($valis['nickname'] == $valu['username']){
                            unset($xinmemarr[$m]);
                        }
                    }
                }
                foreach($xinmemarr as $valn){
                    $listres[] = [
                        'avatar' => $valn['avatar'],
                        'nickname' => $valn['username'],
                        'time' => substr($valn['create_time'],0,10),
                        'indexnickname' => $indexnick,
                        'totalaccount' => ""
                    ];
                }
            }
            $resarr['membernum'] = \app\common\model\Team::alias('t')->join('user u','t.get_user_id=u.id')->where('t.user_id',$this->auth->id)->where('u.level',1)->count() + /*$yuanzaitem_res['data']['data']['group_data'][1]['number']*/count(array_values(array_column($yuanzaitem_res['data']['data']['group_data'][1]['list'], NULL, 'username')));
            $resarr['vipnum'] = \app\common\model\Team::alias('t')->join('user u','t.get_user_id=u.id')->where('t.user_id',$this->auth->id)->where('u.level',2)->count() + /*$yuanzaitem_res['data']['data']['group_data'][2]['number']*/count(array_values(array_column($yuanzaitem_res['data']['data']['group_data'][2]['list'], NULL, 'username')));
            $resarr['subdstrictnum'] = $tyid == 3 && $indexmen['level'] == 4 ? count($souceres) : \app\common\model\Team::alias('t')->join('user u','t.get_user_id=u.id')->where('t.user_id',$this->auth->id)->where('u.level',3)->count() + $yuanzaitem_res['data']['data']['group_data'][3]['number'];
            $resarr['communitynum'] = \app\common\model\Team::alias('t')->join('user u','t.get_user_id=u.id')->where('t.user_id',$this->auth->id)->where('u.level',4)->count() + /*$yuanzaitem_res['data']['data']['group_data'][4]['number']*/count(array_values(array_column($yuanzaitem_res['data']['data']['group_data'][4]['list'], NULL, 'username')));
            $resarr['list'] = $listres ?: [];
            $this->success('成功',$resarr);
        }
        $this->error(__('非法请求'));
    }

    /**
	 *join code
	 */
	public function invitationcode()
	{
		//
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost() && $this->request->post('code')) {
            $code = $this->request->post('code');
            if($code == $this->auth->id) $this->error('不可以邀请自己');
            if(model('\app\common\model\Team')->where('get_user_id',$this->auth->id)->find()) $this->error('已有推荐人');
            model('\app\common\model\Team')->save([
                'user_id' => $code,
                'get_user_id' => $this->auth->id
            ]);
			$this->success('成功');
		}
		$this->error(__('非法请求'));
	}

    /**
     *get place rank
     */
    public function ranking()
    {
        //some
        $sefres = model('app\common\model\Teamprize')->where(['uid' => $this->auth->id,'month' => date('Ym')])->find();
        $useplac=\app\common\model\AddressLocation::where('uid',$this->auth->id)->find();
        if(!$sefres) $sefres['cityid'] = $useplac['city_id'] ?: model('app\api\model\wanlshop\Address')->where('user_id', $this->auth->id)->find()['city_id'];
        $rakarr = \app\common\model\Teamprize::where('cityid',$sefres['cityid'])->where('month',date('Ym'))->order('num DESC')->limit(10)->select();
        $indx = $rakarr ? 10-count($rakarr) : 10;
        $basinx = $rakarr ? count($rakarr) : 0;
        for($i=0;$i<$indx;$i++){
            $rakarr[$basinx+$i] = ['uid' => 0,'num' => 0];
        }
        foreach($rakarr as $key => $val){
            $resultarr[$key]['no'] = $key + 1;
            $resultarr[$key]['nickname'] = \app\common\model\User::where('id',$val['uid'])->find()['nickname'] ?: ($key==0?'该地区本月还无发放':'-');
            $resultarr[$key]['num'] = $val['num'] ?: '-';
        }
        $dectol = \app\common\model\Teamprize::where('cityid',$sefres['cityid'])->where('month',date('Ym'))->sum('num');
        $inputarr['firstmoney'] = '￥'.sprintf("%.2f", 30*$dectol*0.55);
        $inputarr['secondmoney'] = '￥'.sprintf("%.2f", 30*$dectol*0.3);
        $inputarr['thirdmoney'] = '￥'.sprintf("%.2f", 30*$dectol*0.15);
        foreach(\app\common\model\Teamprize::where('cityid',$sefres['cityid'])->where('month',date('Ym'))->order('num DESC')->select() as $mkey=>$mval){
            if($mval['uid'] == $this->auth->id) $innub = $mkey+1;
        }

        if ($useplac || model('app\api\model\wanlshop\Address')->where('user_id', $this->auth->id)->find()) {
            $inputarr['place'] = $useplac['city_id'] ? \app\common\model\Area::where('id',$useplac['city_id'])->find()['name'] : ($useplac['city']?:model('app\api\model\wanlshop\Address')->where('user_id', $this->auth->id)->find()['city']);
            $inputarr['mysel'] = $innub ?: '-';
            $inputarr['rlist'] = $resultarr;
            $this->success('成功',$inputarr);
        }
        $this->error(__('尚未归属地区'));
    }

    protected function createSign($data){
	    $dataTmp = [];
	    foreach ($data as $key => $val){
	        if(!empty($val)){
                $dataTmp[$key] = $val;
            }
        }
	    ksort($dataTmp);
	    $stringSignTemp = http_build_query($dataTmp) . '&key=hl4wJp0c1ud0FLcc';
	    unset($dataTmp);
	    $md5 = md5($stringSignTemp);
	    unset($stringSignTemp);
	    return strtoupper($md5);
    }
}